<?php
	class Booking extends CI_Model {
	
		function __construct(){
			// Call the Model constructor
			parent::__construct();
		}
		
		function get_availability($date,$branch){
			$num_rooms = 0;
			$query = $this->db->get_where('reservations', array('check_in_date' => $date, 'branch_id' => $branch));
			if ($query->num_rows() > 0){
				foreach ($query->result() as $row){
					$num_rooms+=$row->no_of_room;
				}
				return $num_rooms;
			}else{
				return $query->num_rows();
			}
		}
		
		function insert_booking($customer_data,$reserve_data){
			$customer = $this->db->get_where('customers', $customer_data);
			if($customer->num_rows() == 0){
				$this->db->insert('customers', $customer_data);
				$customer = $this->db->get_where('customers', $customer_data);
			}
			$row = $customer->row_array();
			$reserve_data['customer_id'] = $row['customer_id'];
			$this->db->insert('reservations', $reserve_data);
			$reserve_id = $this->get_reserveID($reserve_data);
			return $reserve_id;
		}
		
		function get_reserveID($data){
			$query = $this->db->get_where('reservations',$data);
			if ($query->num_rows() > 0){
				$row = $query->row_array();
				return $row['reserve_id'];
			}else{
				return false;
			}
		}
		
		function get_room($branch,$date,$out_date){
			$data = array();
			$room_reserve = $this->db->query("SELECT distinct room_id FROM rooms WHERE branch_id = '$branch' and room_id NOT IN (SELECT room_id FROM room_reservations JOIN reservations ON reservations.reserve_id = room_reservations.reservation_id WHERE branch_id = '$branch' AND (check_in_date BETWEEN '$date' and '$out_date' OR check_out_date BETWEEN '$date' and '$out_date'))");
			if ($room_reserve->num_rows() > 0){
				//return $room_reserve->num_rows();
				return $room_reserve->result();
			}else{
				return 0;
			}
		}
		
		function room_reserve($reserve_id,$rooms,$rooms_result){
			if($rooms_result != 0){
				for($i=0;$i<$rooms;$i++){
					$room_id = $rooms_result[$i]->room_id;
					$this->db->insert('room_reservations',array('reservation_id' => $reserve_id, 'room_id' => $room_id));
				}
			}else{
				for($i=1;$i<=$rooms;$i++){
					$this->db->insert('room_reservations',array('reservation_id' => $reserve_id, 'room_id' => $i));
				}
			}
		}
	}
?>